# $Id: OnceForm.pm,v 1.1.1.1 2004/02/21 18:48:07 ibo Exp $

package CGI::FOGE2::OnceForm;
use strict;

require 5.006;

use CGI::FOGE2::Form;
use CGI::FOGE2::Tools;
use POSIX qw(strftime);
use CGI::Carp qw(fatalsToBrowser);
# use CGI qw(:standard);
# use CGI qw(-no_xhtml);
use CGI::Pretty qw(-no_xhtml :standard);

our @ISA = qw(CGI::FOGE2::Form);

=head1 NAME

OnceForm

=head1 DESCRIPTION

This subclass of Form corresponds to a form served to authenticated
users only (via https). Moreover an authenticated user may only answer
the form a limited number of times (by default only once).

OnceForm have only one parameter. The limit parameter (1 by default)
limits the number of answers that may be isseud by an authenticated
user.

=cut

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my %args = @_;
    my $self = CGI::FOGE2::Form->new(@_);
    if ( defined $args{'limit'} ) {
        $self->{limit} = $args{'limit'};
    } else {
        $self->{limit} = 1;
    }
    bless $self, $class;
}

sub serve {
    my $self = shift;
    
    $self->check_answers_limit();
    $self->SUPER::serve(@_);
}

sub handle_submission {
    my $self = shift;
    my ($STH) = @_;
    
    $self->check_answers_limit();
    $self->SUPER::handle_submission($STH);
}

sub check_answers_limit {
    my $self = shift;

    # Even if we just select the DB below, we'll write soon in it:
    my $db = $self->dbh_w(); 
    die msg->die_nodbhandle unless defined $db; # extraneous

    if ( CGI::https() ) {
        my $who = CGI::remote_user();
        my $answerTable = $self->{dbAnswer};
        my $request = "select count(*) 
from $answerTable where enquiry = ? and remote_user = ?;";
        my $sth = $db->prepare($request)
            || die "Cannot prepare check request: " . $db->errstr;
        $sth->execute($self->{enquiry}, $who)
            || die "Cannot execute check request: " . $db->errstr . "\n";
        my @row = $sth->fetchrow_array();
        if ( @row ) {
            my ($n) = @row;
            if ( $n >= $self->{limit} ) {
                die sprintf msg->die_alreadyanswered, $who, $n;
            };
        };
        $sth->finish();
    } else {
        die sprintf msg->die_nonauthenticatedperson;
    }
}

1;

# end of OnceForm.pm
